# -* - coding: UTF-8 -* -
#import sys
#reload(sys) 
#sys.setdefaultencoding('utf8')
#工厂中心，负责分配任务
import threading,string,os,sys,importlib,time
from task import *
import logging

#从外部队列读取消息放入内部对列
class ServiceCenter():  
	def __init__(self):
		self.serviceList = {}
		self.queueList = []
		self.loadService()
		self.taskHash = {}
		
	def loadService(self):
		dir_path =os.path.abspath(os.path.dirname(__file__))
		app_path = os.path.join(dir_path, "Service")
		sys.path.append(app_path)
		for root, dirs, files in os.walk(app_path, topdown=False):
			for module in files:
				if module.endswith('command.py'):
					sys.path.append(root)
					name = os.path.basename(root)
					className = name.capitalize()+'Command'
					m = importlib.import_module(name+'.command')
					Commander = getattr(m,className)
					self.register(name,Commander())
					logging.error('Register Service:'+name)
					
	#读取暂存的命令
	def register(self,type,factory):
		self.serviceList[type]=factory
	
	def get(self,type):
		return self.serviceList[type]
		
	def check(self,task):
		return task.type in self.serviceList	

	def register_queue(self,queue):
		self.queueList.append(queue)
		
	def get_queue(self):
		return self.queueList[0]
		
	def do_command(self,command):
		for type in self.serviceList:
			service =  self.serviceList[type]
			if hasattr(service, command):
				func = getattr(service, command)
				if func:
					try:
						response=func(self.get_queue())
					except Exception as e:
						logging.error('ServiceCenter.'+command)
						logging.exception(e)
						time.sleep(0.1)
	
	def start(self):
		self.do_command('start')
		
	def stop(self):
		self.do_command('stop')
		
	#执行命令
	def execute(self,task,queue=False):
		
		if task.type in self.serviceList:
			service =  self.serviceList[task.type]
			logging.info('Execute Service:'+task.type)
			if hasattr(service, task.command):
				func = getattr(service, task.command)		#根据函数名获得函数
				if func:
					#10秒内执行过不重复执行
					hashKey = ''
					if task.unique_time>0:
						hashKey = task.makeHash()
						curTime = time.time()
						if hashKey in self.taskHash and (curTime-self.taskHash[hashKey])<task.unique_time:
							logging.info('Alreadly Execute :'+task.type+' '+task.command)
							return False
						self.taskHash[hashKey] = curTime
					try:
						#print('task.data',task.data)
						response=func(task.data,self.get_queue())
						return response
					except Exception as e:
						if task.unique_time>0 and hashKey:
							del self.taskHash[hashKey]
						logging.error('ServiceCenter.execute')
						logging.exception(e)
						time.sleep(0.1)
						return False
				else:
					return False
			else:
				return False
		else:
			return False